<template>
  <view class="nutrition-container">
    <!-- 用户营养需求 -->
    <view class="nutrition-needs">
      <view class="section-title">您的营养需求</view>
      <view class="needs-card">
        <view class="need-item">
          <text class="need-label">能量</text>
          <text class="need-value">{{ nutritionNeeds.energy }}千卡</text>
        </view>
        <view class="need-item">
          <text class="need-label">蛋白质</text>
          <text class="need-value">{{ nutritionNeeds.protein }}g</text>
        </view>
        <view class="need-item">
          <text class="need-label">脂肪</text>
          <text class="need-value">{{ nutritionNeeds.fat }}g</text>
        </view>
        <view class="need-item">
          <text class="need-label">碳水化合物</text>
          <text class="need-value">{{ nutritionNeeds.carbohydrate }}g</text>
        </view>
      </view>
    </view>

    <!-- 已选菜品 -->
    <view class="selected-dishes">
      <view class="section-title">
        已选菜品 ({{ selectedDishes.length }})
        <button class="clear-btn" @click="clearAll" v-if="selectedDishes.length > 0">
          清空
        </button>
      </view>
      
      <view v-if="selectedDishes.length === 0" class="empty-state">
        <text>点击下方按钮获取MOPSO营养优化方案</text>
        <button class="goto-recommend" @click="generatePlan" :loading="generating">
          {{ generating ? '正在生成...' : '获取营养方案' }}
        </button>
      </view>
      
      <view v-else class="dish-list">
        <view 
          class="dish-item" 
          v-for="(dish, index) in selectedDishes" 
          :key="dish.id"
        >
          <image :src="dish.image" class="dish-image" />
          <view class="dish-info">
            <text class="dish-name">{{ dish.name }}</text>
            <text class="dish-desc">{{ dish.description }}</text>
          </view>
          <view class="dish-actions">
            <button class="optimize-btn" @click="optimizeDish(dish)" :loading="optimizing">
              {{ optimizing ? '优化中...' : '营养优化' }}
            </button>
            <button class="remove-btn" @click="removeDish(index)">移除</button>
          </view>
        </view>
      </view>
    </view>

    <!-- 生成营养方案 -->
    <view class="generate-plan">
      <button class="plan-btn" @click="generatePlan" :loading="generating">
        {{ generating ? 'MOPSO优化中...' : '生成MOPSO营养方案' }}
      </button>
      <view class="plan-tip">
        <text>🧪 基于MOPSO多目标粒子群优化算法，智能匹配您的营养需求</text>
      </view>
    </view>

    <!-- 营养方案结果 -->
    <view class="nutrition-plans" v-if="nutritionPlans.length > 0">
      <view class="section-title">营养方案 (共{{ nutritionPlans.length }}套)</view>
      <view 
        class="plan-item" 
        v-for="(plan, index) in nutritionPlans" 
        :key="index"
      >
        <view class="plan-header">
          <text class="plan-title">方案{{ index + 1 }}</text>
          <view class="plan-accuracy">
            <text>营养偏差率: {{ plan.deviationRate }}%</text>
          </view>
        </view>
        
        <view class="ingredient-list">
          <view 
            class="ingredient-item" 
            v-for="ingredient in plan.ingredients" 
            :key="ingredient.name"
          >
            <view class="ingredient-info">
              <text class="ingredient-name">{{ ingredient.name }}</text>
              <text class="ingredient-amount">{{ ingredient.amount }}g</text>
            </view>
            <view class="nutrition-info">
              <text class="nutrition-item">能量: {{ ingredient.energy }}千卡</text>
              <text class="nutrition-item">蛋白质: {{ ingredient.protein }}g</text>
              <text class="nutrition-item">脂肪: {{ ingredient.fat }}g</text>
              <text class="nutrition-item">碳水: {{ ingredient.carbohydrate }}g</text>
            </view>
          </view>
        </view>
        
        <button class="adopt-plan" @click="adoptPlan(plan)">采用此方案</button>
      </view>
    </view>
  </view>
</template>

<script>
import { getOptimization, getHybridRecommendation } from '@/api/diet'

export default {
  data() {
    return {
      nutritionNeeds: {
        energy: 0,
        protein: 0,
        fat: 0,
        carbohydrate: 0
      },
      selectedDishes: [],
      nutritionPlans: [],
      generating: false,
      optimizing: false,
      optimizedResults: []
    }
  },
  onShow() {
    this.loadSelectedDishes()
    this.loadNutritionNeeds()
  },
  methods: {
    loadSelectedDishes() {
      this.selectedDishes = uni.getStorageSync('selectedDishes') || []
    },
    
    async loadNutritionNeeds() {
      // 模拟用户营养需求数据
      this.nutritionNeeds = {
        energy: 2000,
        protein: 60,
        fat: 67,
        carbohydrate: 250
      }
    },
    
    removeDish(index) {
      this.selectedDishes.splice(index, 1)
      uni.setStorageSync('selectedDishes', this.selectedDishes)
      // 清空之前的方案
      this.nutritionPlans = []
    },
    
    clearAll() {
      uni.showModal({
        title: '确认清空',
        content: '确定要清空所有已选菜品吗？',
        success: (res) => {
          if (res.confirm) {
            this.selectedDishes = []
            this.nutritionPlans = []
            uni.removeStorageSync('selectedDishes')
          }
        }
      })
    },
    
    gotoRecommend() {
      uni.switchTab({
        url: '/pages/diet/recommend/index'
      })
    },
    
    async generatePlan() {
      try {
        this.generating = true
        const userId = this.getUserId()
        console.log('🍽️ 开始生成营养方案, 用户ID:', userId)
        
        // 调用MOPSO营养优化接口
        const res = await getOptimization(userId)
        console.log('📊 营养优化结果:', res)
        
        if (res.selected_dishes && res.selected_dishes.length > 0) {
          // 将MOPSO结果转换为营养方案格式
          const plan = {
            deviationRate: this.calculateDeviationRate(res.nutrition_totals),
            ingredients: res.selected_dishes.map(dish => ({
              name: dish.dish_name,
              amount: Math.round(dish.portion_g || 100),
              energy: Math.round(dish.calories || 0),
              protein: Math.round(dish.protein || 0),
              fat: Math.round(dish.fat || 0),
              carbohydrate: Math.round(dish.carbohydrate || 0)
            }))
          }
          this.nutritionPlans = [plan]
          uni.showToast({
            title: '营养方案生成成功',
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '暂无合适的营养方案',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('生成营养方案失败:', error)
        uni.showToast({
          title: '生成方案失败',
          icon: 'none'
        })
      } finally {
        this.generating = false
      }
    },
    
    async optimizeDish(dish) {
      try {
        this.optimizing = true
        const userId = this.getUserId()
        console.log('🍽️ 开始优化菜品:', dish.name)
        
        const res = await getOptimization(userId)
        
        if (res.selected_dishes && res.selected_dishes.length > 0) {
          this.showOptimizedResults(dish, res)
        } else {
          uni.showToast({
            title: '暂无优化方案',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('优化菜品失败:', error)
        uni.showToast({
          title: '优化失败',
          icon: 'none'
        })
      } finally {
        this.optimizing = false
      }
    },
    
    showOptimizedResults(dish, result) {
      const totals = result.nutrition_totals
      const content = `优化后营养成分：\n` +
        `热量: ${totals.calories}千卡\n` +
        `蛋白质: ${totals.protein}g\n` +
        `脂肪: ${totals.fat}g\n` +
        `碳水化合物: ${totals.carbohydrate}g\n` +
        `纤维: ${totals.fiber}g\n\n` +
        `推荐菜品数: ${result.total_dishes}个`
      
      uni.showModal({
        title: `营养优化结果`,
        content: content,
        showCancel: false,
        confirmText: '知道了'
      })
    },
    
    adoptPlan(plan) {
      uni.showModal({
        title: '采用方案',
        content: `确定采用方案吗？营养偏差率为${plan.deviationRate}%`,
        success: (res) => {
          if (res.confirm) {
            // 保存采用的方案
            uni.setStorageSync('adoptedPlan', plan)
            uni.showToast({
              title: '方案已保存',
              icon: 'success'
            })
          }
        }
      })
    },
    
    getUserId() {
      let userId = uni.getStorageSync('userId')
      if (!userId || userId === 'undefined' || isNaN(userId)) {
        userId = 100
        uni.setStorageSync('userId', userId)
      }
      return Number(userId)
    },
    
    calculateDeviationRate(nutritionTotals) {
      if (!nutritionTotals) return '0.0'
      
      // 计算与目标的偏差率
      const energyDiff = Math.abs(nutritionTotals.calories - this.nutritionNeeds.energy) / this.nutritionNeeds.energy
      const proteinDiff = Math.abs(nutritionTotals.protein - this.nutritionNeeds.protein) / this.nutritionNeeds.protein
      const fatDiff = Math.abs(nutritionTotals.fat - this.nutritionNeeds.fat) / this.nutritionNeeds.fat
      const carbDiff = Math.abs(nutritionTotals.carbohydrate - this.nutritionNeeds.carbohydrate) / this.nutritionNeeds.carbohydrate
      
      const avgDeviation = (energyDiff + proteinDiff + fatDiff + carbDiff) / 4 * 100
      return avgDeviation.toFixed(1)
    }
  }
}
</script>

<style lang="scss" scoped>
.nutrition-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  color: #333;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.clear-btn {
  font-size: 24rpx;
  color: #ff4d4f;
  background: none;
  border: none;
  padding: 0;
}

.needs-card {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.need-item {
  width: 48%;
  text-align: center;
  margin-bottom: 20rpx;
}

.need-label {
  display: block;
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.need-value {
  display: block;
  font-size: 28rpx;
  font-weight: bold;
  color: #1890ff;
}

.empty-state {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
}

.goto-recommend {
  margin-top: 30rpx;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 30rpx;
  padding: 20rpx 40rpx;
}

.dish-list {
  margin-bottom: 30rpx;
}

.dish-item {
  background: white;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  display: flex;
  align-items: center;
}

.dish-image {
  width: 120rpx;
  height: 120rpx;
  border-radius: 12rpx;
  margin-right: 20rpx;
}

.dish-info {
  flex: 1;
}

.dish-name {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.dish-desc {
  font-size: 24rpx;
  color: #666;
}

.dish-actions {
  display: flex;
  gap: 10rpx;
}

.optimize-btn {
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  flex: 1;
}

.remove-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 20rpx;
  padding: 10rpx 20rpx;
  font-size: 24rpx;
  flex: 1;
}

.generate-plan {
  margin-bottom: 30rpx;
}

.plan-btn {
  width: 100%;
  height: 80rpx;
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 40rpx;
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
}

.plan-tip {
  text-align: center;
  font-size: 24rpx;
  color: #666;
  line-height: 1.5;
}

.plan-item {
  background: white;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.plan-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.plan-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
}

.plan-accuracy {
  font-size: 24rpx;
  color: #52c41a;
}

.ingredient-item {
  margin-bottom: 20rpx;
  padding: 20rpx;
  background: #f9f9f9;
  border-radius: 12rpx;
}

.ingredient-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.ingredient-name {
  font-size: 26rpx;
  font-weight: bold;
  color: #333;
}

.ingredient-amount {
  font-size: 26rpx;
  color: #1890ff;
  font-weight: bold;
}

.nutrition-info {
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.nutrition-item {
  font-size: 22rpx;
  color: #666;
  width: 48%;
  margin-bottom: 5rpx;
}

.adopt-plan {
  width: 100%;
  height: 60rpx;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 30rpx;
  font-size: 26rpx;
  margin-top: 20rpx;
}
</style>